<?php
namespace App\Http\Controllers\Api\Hldy;

use App\Fishing;
use App\FishingItem;
use App\GameZghpt;
use App\Http\Controllers\Controller;
use App\Jobs\SendWechatMessage;
use App\User;
use App\UserCoinLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class FishingController extends Controller 
{
    private $reward_count = 2;

	private function config()
    {
        //配置的版本
        $config['config_id'] = 1;
        //控制下杆的时间
        $config['do_time'] = 3;
        //每天允许亏的金额
        $config['kui_je'] = 2000;
        //每种鱼的赔率
        $config['fish_times_info'] = [
            1 => ['id' => 1, 'name' => '小彩鱼', 'times' => 0.3],
            2 => ['id' => 2, 'name' => '小丑鱼', 'times' => 0.6],
            3 => ['id' => 3, 'name' => '蝴蝶鱼', 'times' => 1],
            4 => ['id' => 4, 'name' => '海南红鱼', 'times' => 2],
            5 => ['id' => 5, 'name' => '灯笼鱼', 'times' => 3],
            6 => ['id' => 6, 'name' => '厚唇鱼', 'times' => 5],
            7 => ['id' => 7, 'name' => '鲨鱼', 'times' => 15],
        ];
        //所有鱼命中概率
        $config['fish_hit_rate'] = [
            1 => ['id' => 1, 'name' => '小彩鱼', 'rate' => 65],
            2 => ['id' => 2, 'name' => '小丑鱼', 'rate' => 25],
            3 => ['id' => 3, 'name' => '蝴蝶鱼', 'rate' => 5],
            4 => ['id' => 4, 'name' => '海南红鱼', 'rate' => 3],
            5 => ['id' => 5, 'name' => '灯笼鱼', 'rate' => 2],
            6 => ['id' => 6, 'name' => '厚唇鱼', 'rate' => 1],
            7 => ['id' => 7, 'name' => '鲨鱼', 'rate' => 1],
        ];
        //一杆钓N条鱼的条数概率
        $config['hit_num_rate'] = [[
            0 => ['id' => 0, 'rate' => 35],
            1 => ['id' => 1, 'rate' => 35],
            2 => ['id' => 2, 'rate' => 15],
            3 => ['id' => 3, 'rate' => 5],
            4 => ['id' => 4, 'rate' => 2],
            5 => ['id' => 5, 'rate' => 1],
            6 => ['id' => 6, 'rate' => 1],
            7 => ['id' => 7, 'rate' => 1],
            8 => ['id' => 8, 'rate' => 1],
            9 => ['id' => 9, 'rate' => 1],
            10 => ['id' => 10, 'rate' => 1],
        ], [
            0 => ['id' => 0, 'rate' => 55],
            1 => ['id' => 1, 'rate' => 55],
            2 => ['id' => 2, 'rate' => 15],
            3 => ['id' => 3, 'rate' => 5],
            4 => ['id' => 4, 'rate' => 2],
            5 => ['id' => 5, 'rate' => 1],
            6 => ['id' => 6, 'rate' => 1],
            7 => ['id' => 7, 'rate' => 1],
            8 => ['id' => 8, 'rate' => 1],
            9 => ['id' => 9, 'rate' => 1],
            10 => ['id' => 10, 'rate' => 1],
        ]];

        //金币列表(其他金额视为非法下杆)
        $config['gold_list'] = [
            1 => 1,
            2 => 5,
            3 => 10,
            4 => 50
        ];

        return $config;
    }

    public function doFish( Request $request )
    {
		$config = $this->config();
		$user   = auth()->user();
        //获取用户的mid
        $mid = $user->id;
        //获取用户下杆的金额
        $je = $request->input('goldnum');

        if (! in_array($je, $config['gold_list'])) {
            $da['msg'] = '金额非法';
            $da['code'] = 1;
            $da['data'] = [];
            $da['balance'] = $user->XYB;
            return response()->json($da);
        }
            //获取用户实际下杆的金额
        // $xg_jb = $config['gold_list'][$je];
        $xg_jb = $je;

        //检查用户的小妖币余额
        if (!$this->check_jb($mid, $xg_jb)) {
            $da['msg'] = '小妖币不足，请充值';
            $da['code'] = 1;
            $da['data'] = [];
            $da['balance'] = $user->XYB;
            return $da;
        }
        $now = time();
        $ukey = $user->id . '-' . $now;

        //钓到数据
        $data = [
            'fish' => [],
        ];

        try {
	        //开启数据库事务
	        DB::beginTransaction();
	        // $this->db->trans_start();
	        //扣除金额
	        $this->jb($mid, -$xg_jb, '钓鱼游戏扣除');

            //用户玩游戏状态更新
            $user->update(['status' => DB::raw('status|4')]);

	        //检查用户的小妖币余额
	        if (!$this->check_jb($mid, $xg_jb)) {
	            // $this->db->trans_rollback();
	            DB::rollBack();
	            $da['msg'] = '小妖币不足，请充值';
	            $da['code'] = 1;
	            $da['data'] = [];
            	$da['balance'] = $user->XYB;
	            return $da;
	        }

	        $do_fishiing = $this->do_fishiing($config, $xg_jb, $mid);
            $data['fish'] = $do_fishiing['fish'];

	        $fishing = new Fishing();
	        $fishing->mid = $mid;
	        $fishing->xg_jb = $xg_jb;
	        $fishing->sh_jb = $do_fishiing['sh_jb'];
	        $fishing->numb = $do_fishiing['numb'];
	        $fishing->config_id = $config['config_id'];
	        $fishing->mktime = $now;
	        $fishing->date = date('Ymd');
	        $fishing->ukey   = $ukey;
	        $fishing->save();

	        // $in['mid'] = $mid;
	        // $in['xg_jb'] = $xg_jb;
	        // $in['sh_jb'] = $do_fishiing['sh_jb'];
	        // $in['numb'] = $do_fishiing['numb'];
	        // $in['config_id'] = $config['config_id'];
	        // $in['mktime'] = time();
	        // $this->db->insert('fishing', $in);
	        // //获取插入数据的id
	        // $id = $this->db->insert_id();

	        //检查上一数据插入的时间

	        // $this->db->limit(1);
	        // $this->db->order_by('id', 'desc');
	        // $this->db->where('id <', $id);
	        // $q = $this->db->get_where('fishing', array('mid' => $mid));

	        $last_mktime = Fishing::where('id', '<', $fishing->id)->where('mid', $mid)->orderBy('id', 'desc')->value('mktime');
	        $last_mktime = $last_mktime ? $last_mktime : 0;

	        // $last_da = $q->row_array(0);
	        if ($now - $last_mktime < $config['do_time']) {
	            DB::rollBack();
	            $da['msg'] = '时间冲突，请稍后下杆。';
	            $da['code'] = 1;
	            $da['data'] = [];
            	$da['balance'] = $user->XYB;
	            return $da;
	        }

	        //记录钓到了哪些鱼
	        foreach ($do_fishiing['item'] as $v) {
	            // $in_item['fishing_id'] = $id;
	            // $in_item['fish_id'] = $v;
	            // $in_item['mid'] = $mid;
	            // $in_item['mktime'] = time();
	            // $this->db->insert('fishing_item', $in_item);
	            $fishingItem = new FishingItem();
	            $fishingItem->fishing_id = $fishing->id;
	            $fishingItem->fish_id = $v;
	            $fishingItem->mid = $mid;
	            $fishingItem->mktime = time();
	            $fishingItem->save();
	        }

	        //添加钓鱼金额
	        $this->jb($mid, $do_fishiing['sh_jb'], '钓鱼游戏获取');

            $this->rewardFinder($user, $do_fishiing['sh_jb']);

	        //提交全部的数据
	        DB::commit();
	    } catch (\Exception $e) {
            DB::rollBack();
            Log::debug($e);
            $da['msg'] = '系统错误，请退出重新进入';
	        $da['code'] = 1;
            $da['balance'] = $user->XYB;
	        $da['data'] = [];
	        return $da;
        }

        $da['msg'] = '钓鱼成功';
        $da['code'] = 0;
//        $da['info'] = $do_fishiing;
        $da['balance'] = $user->XYB;
        $da['fishNum'] = $do_fishiing['numb'];
        $da['totalGold'] = $do_fishiing['sh_jb'];
        $da['data'] = $data;

        //取得当前用户是否出现财神到 
        $user = new \App\Tools\User\User();
        $da['isCaiShen'] = $user->getUserIsCoupon($mid);
        return response()->json($da);

    }

    //钓鱼随机
    private function do_fishiing($config, $je, $mid)
    {
        //判断今天是否已经超出额度
        // $this->db->select('sum(xg_jb),snum(sh_jb)');
        // $this->db->where('date', date('Ymd'));
        // $q = $this->db->get_where('fishiing');
        // $fishing = $q->row_array(0);

        $hit_num_rate = $config['hit_num_rate'][0];

        $jb_diff = Fishing::where('date', date('Ymd'))->selectRaw('sum(sh_jb-xg_jb) s')->value('s');

        $da = [];
        //今天，亏了超过2000人民币
        if (($jb_diff > $config['kui_je']) && in_array($je, [10, 50])) {
            $da['numb'] = 0;
            $da['sh_jb'] = 0;
            $da['item'] = array();
            $da['fish'] = [];
            return $da;
        }

        //单个用户当天超过800执行低概率
        $jb_diff = Fishing::where('date', date('Ymd'))->where('mid', $mid)->selectRaw('sum(sh_jb-xg_jb) s')->value('s');
        if ($jb_diff > 800) {
            $hit_num_rate = $config['hit_num_rate'][1];
        }

        //随机看看可以钓到多少条鱼
        $da['numb'] = $this->get_rand($hit_num_rate);

        //随机看看钓到哪些鱼
        if ($da['numb'] > 0) {
        	$da['sh_jb'] = 0;
            for ($i = 0; $i < $da['numb']; $i++) {
                $da['item'][$i] = $this->get_rand($config['fish_hit_rate']);
                $da['sh_jb'] += ($config['fish_times_info'][$da['item'][$i]]['times'] * $je);
                $da['fish'][$i] = $config['fish_times_info'][$da['item'][$i]];
                $da['fish'][$i]['num'] = 1;
                $da['fish'][$i]['gold'] = ($config['fish_times_info'][$da['item'][$i]]['times'] * $je);
            }
        } else {
            $da['sh_jb'] = 0;
            $da['item'] = array();
            $da['fish'] = [];
        }
        return $da;
    }

    //随机算法
    private function get_rand($rand)
    {
        $result = '';
        //概率数组的总概率精度
        $sum = 0;
        foreach ($rand as $v) {
            $sum += $v['rate'] * 100;
        }

        //概率数组循环
        foreach ($rand as $v) {
            $rate = $v['rate'] * 100;
            //抽取随机数
            $rand_num = mt_rand(1, $sum);
            if ($rand_num <= $rate) {
                //得出结果
                $result = $v['id'];
                break;
            } else {
                $sum -= $rate;
            }
        }

        unset ($rand);
        return $result;
    }

	//检查小妖币数据是否小于零
    private function check_jb($mid)
    {
        return UserCoinLog::totalXyb( $mid ) > 0;
    }

	//添加小妖币
    private function jb($mid, $je, $content)
    {
    	$key = '2-'. $mid . '-' . $je . '-' . time();
    	UserCoinLog::log(2, $mid, 1, $je, $content, $key);
    }

    /**
     * 奖励上级
     */
    private function rewardFinder($user, $total)
    {
        if ($this->reward_count) {
            if ($finder = User::where('id', $user->finder_id)->first()) {
                if (floatval($xyb = bcmul($total, 0.01, 2))) {
                    if(!$gameZghpt = $finder->game_zghpt){
                        $gameZghpt = new GameZghpt();
                        $gameZghpt->user_id = $finder->id;
                        $gameZghpt->quota = 0;
                        $gameZghpt->level = 0;
                        $gameZghpt->save();
                    }
                    if($gameZghpt->level) {
                        $tmp_xyb = $xyb * 100;
                        $message = '恭喜您获得' . $tmp_xyb . '个小妖币的推荐奖励。';

                        $key = '2-'. $finder->id . '-' . $xyb . '-' . time() . '-1';
                        UserCoinLog::log( 2, $finder->id, UserCoinLog::TYPE_XYB, $xyb, '推荐奖励', $key );
                    } else {
                        $message = '您好，您错过了'. $xyb .'小妖币的红包，请<a href="http://ga.cloudxt.cn/zghpt/vip/page">立即升级VIP</a>！';
                    }

                    $this->dispatch(new SendWechatMessage($finder->openid, $message));

                    $this->reward_count--;
                    $this->rewardFinder($finder, $total);
                }
            }
        }
    }
}
     